import json
import time

from django.db.models import Count, Subquery, OuterRef
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from stw_app import models
from stw_app.decorator import already_login
from stw_app.models import ChatMessage
from stw_app.models import UserInfo


# 获取想要聊天的群组
@already_login
@csrf_exempt
def get_group(request):
    if request.method == "POST":
        # 从前端传入的发起人的id，目标人的id：
        sender_id = request.POST.get('sender_id')
        receiver_id = request.POST.get('receiver_id')
        order_id = request.POST.get('order_id')
        print(order_id)
        # 在数据库表chat_group中获取聊天群组
        chat_obj = models.ChatGroup.objects.filter(id1=sender_id, id2=receiver_id).first()
        if chat_obj is None:  # 颠倒一下顺序
            chat_obj = models.ChatGroup.objects.filter(id1=receiver_id, id2=sender_id).first()
        if chat_obj is None:  # 还没查到，新建群组
            # 获取当前组里group的最大值，加一
            chat_obj = models.ChatGroup.objects.order_by('-group').first()
            if chat_obj is None:  # 当前表为空
                group = 1
            else:
                group = chat_obj.group + 1

            chat_obj = models.ChatGroup(id1=sender_id, id2=receiver_id, group=group, order_id=order_id)
            chat_obj.save()
        else:
            group = chat_obj.group
            chat_obj.order_id = order_id
            chat_obj.save()
        return JsonResponse({'group': group})


@already_login
@csrf_exempt
def get_any_group(request):
    if request.method == "POST":
        # 从前端传入的发起人的id
        sender_id = request.POST.get('sender_id')
        # 查看chat_group表中是否有该目标人的id
        chat_obj = models.ChatGroup.objects.filter(id1=sender_id).first()
        if chat_obj is None:
            chat_obj = models.ChatGroup.objects.filter(id2=sender_id).first()
        if chat_obj is None:
            # 没有关于当前用户的聊天号
            group = -sender_id
            count_ = models.ChatGroup.objects.count()
            models.ChatGroup.objects.create(
                id=count_ + 1,
                id1=0,  # 系统向用户发送消息
                id2=sender_id,
                group=-sender_id
            )
        else:
            group = chat_obj.group
        return JsonResponse({"success": True, "group": group})


# 获取当前页面的uer_id
@csrf_exempt
def get_userid(request):
    if request.method == 'POST':
        user_obj=models.Code.objects.filter(id1=3).first()
        if user_obj:
            user_id = user_obj.code_1
            return JsonResponse({'userid': user_id, 'success': 1})
        else:
            return JsonResponse({'success': 0})


@csrf_exempt
def get_order(request):
    if request.method == "POST":
        data_list = json.loads(request.body.decode('utf-8'))
        orderid = data_list[0]
        dict_list = []
        order = models.Order.objects.get(
            id=orderid
        )

        dict = {
            'id': order.id,
            'customer_id': order.customer_id,
            'real_worker_id': order.real_worker_id,
            'condition': order.condition,
            'description': order.description,
            'title': order.title,
            'price': order.price,
            'type': order.type,
            'start_time': order.start_time,
            'end_time': order.end_time,
            'release_time': order.release_time,

        }
        dict_list.append(dict)
        return JsonResponse({'data': dict_list, 'success': True})
    return JsonResponse({'success': False})


@already_login
@csrf_exempt
def get_chaters(request):
    if request.method == "POST":
        user_id = request.POST.get('user_id')
        print("!!!user_id=", user_id)

        # Find ChatGroups where the user_id is in either id1 or id2
        chat_groups = models.ChatGroup.objects.filter(Q(id1=user_id) | Q(id2=user_id))
        id_list = set()

        # Extract unique user IDs from ChatGroups
        for group in chat_groups:
            id_list.add(group.id1)
            id_list.add(group.id2)

        # Remove the user's own ID from the list
        id_list.discard(user_id)

        # Fetch user information based on the obtained user IDs
        user_info_list = UserInfo.objects.filter(id__in=id_list)

        response_data = []
        for user_info in user_info_list:
            # Get the latest message between the users
            latest_message = ChatMessage.objects.filter(
                (Q(sender=user_id) & Q(receiver=user_info.id)) |
                (Q(sender=user_info.id) & Q(receiver=user_id))
            ).order_by('-id').first()

            # Get the chat group for the users
            chat_group = models.ChatGroup.objects.filter(
                (Q(id1=user_info.id) & Q(id2=user_id)) | (Q(id1=user_id) & Q(id2=user_info.id))
            ).first()

            top_value = chat_group.top if chat_group else False

            user_data = {
                'id': user_info.id,
                'name': user_info.nick_name,
                'avatar': user_info.avatar,
                'latestMessage': latest_message.content if latest_message else None,
                'latestTime': latest_message.timestamp if latest_message else None,
                'top': top_value,
            }
            response_data.append(user_data)

        return JsonResponse({'users': response_data, 'success': True})


def get_senderid(request):
    if request.method == "POST":
        user_id = request.POST.get('user_id')
        group = request.POST.get('group')
        # 在数据库表chat_group中获取聊天群组
        try:
            chat_obj = models.ChatGroup.objects.filter(group=group, id2=user_id).first()
            sender_id = chat_obj.id1
            user_info = UserInfo.objects.filter(id=sender_id).first()
            name = user_info.nick_name
            return JsonResponse({'senderid': sender_id, 'sendername': name})
        except:
            chat_obj = models.ChatGroup.objects.filter(group=group, id1=user_id).first()
            if chat_obj == None:
                return JsonResponse({'success': False})
            sender_id = chat_obj.id2
            user_info = UserInfo.objects.filter(id=sender_id).first()
            name = user_info.nick_name
            return JsonResponse({'senderid': sender_id, 'sendername': name})


def update_top(request):
    if request.method == "POST":
        group = request.POST.get('group')
        user_id = request.POST.get('user_id')
        top = request.POST.get('top')
        chat_obj = models.ChatGroup.objects.filter(group=group, id2=user_id).first()
        chat_obj.top = top
        chat_obj.save()
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False})


@already_login
@csrf_exempt
def msg_poll(request):
    # 模拟一些异步操作或者等待新数据
    time.sleep(5)
    user_id = request.GET.get('userid', None)
    if user_id == None:
        print('error')
        print(user_id)
        return JsonResponse({'success': False})
    # 查询未读消息，并按照 sender 进行分组，并计算每个 sender 的数量
    unread_messages_count = (
        ChatMessage.objects
        .filter(receiver=user_id, read=False)  # 当前用户未读消息
        .values('sender')
        .annotate(
            message_count=Count('id'),  # 消息数
            latest_message_content=Subquery(
                ChatMessage.objects
                .filter(sender=OuterRef('sender'), receiver=user_id, read=False)
                .order_by('-id')  # 按照 id 降序排序，获取最新的消息
                .values('content')[:1]
            ),
            timeStamp=Subquery(
                ChatMessage.objects
                .filter(sender=OuterRef('sender'), receiver=user_id, read=False)
                .order_by('-id')  # 按照 id 降序排序，获取最新的消息
                .values('timestamp')[:1]
            )
        )
    )
    data = {item['sender']: {
        'message_count': item['message_count'],
        'latest_content': item['latest_message_content'],
        'latestTime': item['timeStamp']}
        for item in unread_messages_count}
    # print(data)
    return JsonResponse(data)


@already_login
@csrf_exempt
def msg_poll2(request):
    # 模拟一些异步操作或者等待新数据
    time.sleep(5)
    user_id = request.GET.get('userid', None)
    if user_id == None:
        print('error')
        print(user_id)
        return JsonResponse({'success': False})
    # 查询未读消息，并按照 sender 进行分组，并计算每个 sender 的数量
    unread_messages_count = (
        ChatMessage.objects
        .filter(receiver=user_id, read=False)  # 当前用户未读消息
        .values('sender')
        .annotate(
            message_count=Count('id'),  # 消息数
            latest_message_content=Subquery(
                ChatMessage.objects
                .filter(sender=OuterRef('sender'), receiver=user_id, read=False)
                .order_by('-id')  # 按照 id 降序排序，获取最新的消息
                .values('content')[:1]
            ),
            timeStamp=Subquery(
                ChatMessage.objects
                .filter(sender=OuterRef('sender'), receiver=user_id, read=False)
                .order_by('-id')  # 按照 id 降序排序，获取最新的消息
                .values('timestamp')[:1]
            )
        )
    )
    data = {item['sender']: {
        'message_count': item['message_count'],
        'latest_content': item['latest_message_content'],
        'latestTime': item['timeStamp']}
        for item in unread_messages_count}
    # print(data)
    return JsonResponse(data)


# 获取已读的消息id
@already_login
@csrf_exempt
def read_msg(request):
    if request.method == 'POST':
        userid = models.Code.objects.filter(id1=3).first().code_1
        id = request.POST.get('id')
        try:
            message = ChatMessage.objects.get(id=id, receiver=userid, read=False)
            # 找到符合条件的记录，更新read字段为True
            message.read = True
            message.save()
            return JsonResponse({'success': False})
        except ChatMessage.DoesNotExist:
            # 没有找到符合条件的记录
            return JsonResponse({'success': False})
    return JsonResponse({'success': False})
